package com.example.xxljobaiassistant.service;

import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @Author xxx
 * @className XxlJobServiceImpl
 * @description //TODO
 * @data 2025/6/16 15:58
 */
@Service
public class XxlJobServiceImpl implements XxlJobService{
    @Value("${xxl-job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl-job.admin.access-token:}")
    private String accessToken;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String listExecutors() {
        try {
            String url = adminAddresses + "/jobgroup/pageList";
            HttpHeaders headers = createHeaders();
            headers.set("X-Requested-With", "XMLHttpRequest");

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("start", "0");
            params.add("length", "100");
            params.add("appname","");
            params.add("title","");

            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, entity, String.class);

            return response.getBody();
        } catch (Exception e) {

            return "{\"code\":500,\"msg\":\"获取执行器列表失败: " + e.getMessage() + "\"}";
        }
    }

    @Override
    public String listJobs() {
        try {
            String url = adminAddresses + "/jobinfo/pageList";
            HttpHeaders headers = createHeaders();

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            // 添加与curl命令相同的参数
            params.add("jobGroup", "2");  // 指定执行器组ID
            params.add("triggerStatus", "-1");  // -1表示所有状态
            params.add("jobDesc", "");  // 任务描述筛选
            params.add("executorHandler", "");  // 执行器处理器筛选
            params.add("author", "");  // 作者筛选
            params.add("start", "0");  // 起始位置
            params.add("length", "100");  // 查询数量

            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, entity, String.class);

            return response.getBody();
        } catch (Exception e) {
            return "{\"code\":500,\"msg\":\"获取任务列表失败: " + e.getMessage() + "\"}";
        }
    }

    @Override
    public String triggerJob(int jobId, String executorParam) {
        try {
            String url = adminAddresses + "/jobinfo/trigger";
            HttpHeaders headers = createHeaders();

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("id", String.valueOf(jobId));
            if (executorParam != null && !executorParam.isEmpty()) {
                params.add("executorParam", executorParam);
            }

            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, entity, String.class);

            return response.getBody();
        } catch (Exception e) {

            return "{\"code\":500,\"msg\":\"触发任务执行失败: " + e.getMessage() + "\"}";
        }
    }

    @Override
    public String queryJobLogs(int jobId, String filterTime, int start, int length) {
        try {
            String url = adminAddresses + "/joblog/pageList";
            HttpHeaders headers = createHeaders();

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("jobId", String.valueOf(jobId));
            if (filterTime != null && !filterTime.isEmpty()) {
                params.add("filterTime", filterTime);
            }
            params.add("start", String.valueOf(start));
            params.add("length", String.valueOf(length));

            // 可以添加其他筛选参数
            params.add("jobGroup", "0");  // 0表示所有执行器
            params.add("logStatus", "-1"); // -1表示所有状态

            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, entity, String.class);

            return response.getBody();
        } catch (Exception e) {
            return "{\"code\":500,\"msg\":\"查询任务日志列表失败: " + e.getMessage() + "\"}";
        }
    }

    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if (accessToken != null && !accessToken.isEmpty()) {
            headers.set("Cookie", accessToken);
        }else{
            headers.set("Cookie", "");
        }
        return headers;
    }
}
